package com.ourchem.web.controller.common;

import java.io.IOException;
import java.util.List;

import com.ourchem.bus.domain.SystemFile;
import com.ourchem.bus.domain.UploadResult;
import com.ourchem.bus.service.ISysFileService;
import com.ourchem.common.config.SmartFurnConfig;
import com.ourchem.common.constant.Constants;
import com.ourchem.common.utils.StringUtils;
import com.ourchem.common.utils.file.FileUtils;
import com.ourchem.common.utils.poi.ExcelUtil;
import com.ourchem.framework.config.ServerConfig;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ourchem.common.annotation.Log;
import com.ourchem.common.core.controller.BaseController;
import com.ourchem.common.core.domain.AjaxResult;
import com.ourchem.common.enums.BusinessType;
import com.ourchem.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ourchem
 * @date 2021-09-10
 */
@RestController
@RequestMapping("/system/file")
public class FileController extends BaseController
{
    @Autowired
    private ISysFileService sysFileService;

    @Autowired
    private ServerConfig serverConfig;

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(SystemFile systemFile)
    {
        startPage();
        List<SystemFile> list = sysFileService.selectSysFileList(systemFile);
        return getDataTable(list);
    }

    /**
     * 文件，图片批量上传
     */
//    @PreAuthorize("@ss.hasPermi('bus:financial:home:pop')")
    @PostMapping("/pop")
    public AjaxResult pop(@RequestParam("file") List<MultipartFile> file, @RequestParam(value = "category", required = false) String category,
                          @RequestParam(value = "columnName", required = false) String columnName) throws IOException {
        List<UploadResult> result = sysFileService.uploadFile(file);
        return AjaxResult.success(result);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SystemFile systemFile)
    {
        List<SystemFile> list = sysFileService.selectSysFileList(systemFile);
        ExcelUtil<SystemFile> util = new ExcelUtil<SystemFile>(SystemFile.class);
        return util.exportExcel(list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:file:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(sysFileService.selectSysFileById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:file:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SystemFile systemFile)
    {
        return toAjax(sysFileService.insertSysFile(systemFile));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:file:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SystemFile systemFile)
    {
        return toAjax(sysFileService.updateSysFile(systemFile));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:file:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysFileService.deleteSysFileByIds(ids));
    }

    @RequestMapping(value = "fileUpload", method = RequestMethod.POST, produces = { "application/json; charset=utf-8" })
    @ApiOperation(value = "文件上传操作", httpMethod = "POST", notes = "文件上传操作")
    @ResponseBody
    public List<UploadResult> fileUpload(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest httpservletrequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> list = httpservletrequest.getFiles("file");
        return sysFileService.uploadFile(list);
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(long id, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            SystemFile file = sysFileService.selectSysFileById(id);
            String resource = file.getFilePath();
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = SmartFurnConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = file.getFileName();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

}
